<?php

namespace App\Console\Commands;

use App\Models\OrderInfo;
use App\Models\ChannelStatistics as ChannelStatisticsModel;
use App\Models\User;
use Illuminate\Console\Command;

class ChannelStatistics extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:channelStatistics';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '渠道统计';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $channels = [
            'hz' => '渠道合作',
            'yl' => '渠道合作',
            'qd' => '营销宣传',
            'default' => '直接访问'
        ];
        $channel_keys = array_keys($channels);
        foreach ($channel_keys as $channel_key) {
            if ($channel_key == 'default') {
                $user_ids = User::where('channel_key', '')->pluck('id');
                $orderInfos = OrderInfo::whereIn('user_id', $user_ids)->where('status', 1)->where('is_verify', 1)->get();
                ChannelStatisticsModel::updateOrCreate(
                    ['channel_key' => $channel_key, 'channel_value' => 'default'],
                    ['type' => $channels[$channel_key], 'user_count' => count($user_ids), 'order_count' => $orderInfos->count(), 'order_amount' => $orderInfos->sum('amount')]
                );
            } else {
                $channel_values = User::where('channel_key', $channel_key)->groupBy('channel_value')->pluck('channel_value');
                foreach ($channel_values as $channel_value) {
                    $user_ids = User::where('channel_key', $channel_key)->where('channel_value', $channel_value)->pluck('id');
                    $orderInfos = OrderInfo::whereIn('user_id', $user_ids)->where('status', 1)->where('is_verify', 1)->get();
                    ChannelStatisticsModel::updateOrCreate(
                        ['channel_key' => $channel_key, 'channel_value' => $channel_value],
                        ['type' => $channels[$channel_key], 'user_count' => count($user_ids), 'order_count' => $orderInfos->count(), 'order_amount' => $orderInfos->sum('amount')]
                    );
                }
            }
        }
    }
}
